package com.heima.common.tess4j;


import com.heima.common.exception.LeadException;
import lombok.Data;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Data
@Component
@ConfigurationProperties(prefix = "tess4j")
public class Tess4jClient {
    private String dataPath;
    private String language;

    public String doOCR(BufferedImage image) throws TesseractException {
        if(StringUtils.isBlank(dataPath)){
            throw new LeadException(500,"Tess4j，图片路径为空！");
        }
        //创建Tesseract对象
        ITesseract tesseract = new Tesseract();
        //设置字体库路径
        tesseract.setDatapath(dataPath);
        //中文识别
        tesseract.setLanguage(language);
        //执行ocr识别
        String result = tesseract.doOCR(image);
        //替换回车和tal键  使结果为一行
        result = result.replaceAll("\\r|\\n", "-").replaceAll(" ", "");
        return result;
    }

//    public static void main(String[] args)throws Exception {
//        File file = new File("e:/test2.png");
//        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(file));
//        Tess4jClient tess4jClient = new Tess4jClient();
//        tess4jClient.setDataPath("e:/");
//        tess4jClient.setLanguage("chi_sim");
//        String src = tess4jClient.doOCR(bufferedImage);
//        System.out.println(src);
//    }
}
